/**
 * Created with JetBrains WebStorm.
 * User: rekey
 * Date: 7/9/13
 * Time: 21:14
 * To change this template use File | Settings | File Templates.
 */
var mongoose = require('mongoose');
var schemas = require('../schemas/index.js');
var schema = schemas['category'];
var when = require('when');

mongoose.model('category', schema);
var model = mongoose.model('category');

function create(data) {
    var deferred = when.defer();
    var Model = new model();
    Object.keys(data).forEach(function(key) {
        Model[key] = data[key];
    });
    Model.save(function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function getList() {
    var t = Date.now();
    var deferred = when.defer();
    model.find({
        type : 'category'
    }, function(err, categories) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(categories);
            console.log('Categories getList 查询费时' + (Date.now() - t) + 'ms');
            t = null;
        }
    });
    return deferred.promise;
}

function getOneBySlug(slug) {
    var deferred = when.defer();
    model.findOne({
        slug : slug
    }, function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function getOneByName(name) {
    console.log(name);
    var deferred = when.defer();
    model.findOne({
        name : name
    }, function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

exports.getOneBySlug = getOneBySlug;
exports.getOneByName = getOneByName;
exports.getList = getList;
exports.create = create;